package com.hcb.micro.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import com.hcb.micro.dto.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hcb.micro.controller.base.BaseControllers;
import com.hcb.micro.sdk.weixin.RequestHandler;
import com.hcb.micro.sdk.weixin.util.MD5Util;
import com.hcb.micro.service.IAccountOpenidService;
import com.hcb.micro.service.IQqbsAccountService;
import com.hcb.micro.service.IQqbsRewardService;
import com.hcb.micro.service.IQqbsWithdrawalsLogService;
import com.hcb.micro.util.CommonHttpClient;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("withdrawals")
public class WithdrawalsController extends BaseControllers{

	@Autowired
	IQqbsWithdrawalsLogService qqbsWithdrawalsLogService;
	
	@Autowired
	IQqbsRewardService qqbsRewardService;
	
	@Autowired
	IQqbsAccountService qqbsAccountService;
	
	@Autowired
	IAccountOpenidService accountOpenidService;
	
	@RequestMapping(value = "list", method = RequestMethod.POST)
	@ResponseBody
	public String listByType() {
		JSONObject json = new JSONObject();
		if (sign == 1) {
			json.put("result", "1");
			json.put("description", "请检查参数格式是否正确或者参数是否完整");
			return buildReqJsonInteger(1, json);
		}
		// 登录认证失败
		if (sign == 2) {
			json.put("result", "2");
			json.put("description", "账号未登录");
			return buildReqJsonInteger(2, json);
		}
		
		HttpSession session = request.getSession();
		Manager manager = (Manager) session.getAttribute("MANAGER");
        if(manager == null){
        	json.put("result", "1");
			json.put("description", "账号未登陆");
			return buildReqJsonObject(json);
        }
		
		JSONObject bodyInfo = JSONObject.fromObject(bodyString);
		
		Map<String,Object> para = new HashMap<>();
		
		if(bodyInfo.get("status") != null && !"".equals(bodyInfo.get("status"))){
			para.put("status", Byte.valueOf(bodyInfo.getString("status")));
		}
		
		List<QqbsWithdrawalsLog> qwwlListAll = qqbsWithdrawalsLogService.selectByPara(para);
		
		if(bodyInfo.get("page") != null && !"".equals(bodyInfo.get("page"))) {
			para.put("start", (Integer.valueOf(bodyInfo.getString("page"))-1)*Integer.valueOf(bodyInfo.getString("pageSize")));
		}
		if(bodyInfo.get("pageSize") != null && !"".equals(bodyInfo.get("pageSize"))) {
			para.put("size", Integer.valueOf(bodyInfo.getString("pageSize")));
		}
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		List<QqbsWithdrawalsLog> qwwlList = qqbsWithdrawalsLogService.selectByPara(para);
		
		if(qwwlList.size() <= 0){
			json.put("result", "1");
			json.put("description", "列表不存在");
			return buildReqJsonObject(json);
		}
		List<Map<String,String>> list = new ArrayList<>();
		for(QqbsWithdrawalsLog qwwl:qwwlList){
			Map<String,String> map = new HashMap<>();

			QqbsAccount account = qqbsAccountService.selectByAccountId(qwwl.getAccountId());
			
			map.put("id", qwwl.getId()+"");
			map.put("accountId", qwwl.getAccountId()+"");
			map.put("accountName", account==null?"":account.getNickname());
			map.put("withdrawals", qwwl.getWithdrawals()+"");
			
			String statusValue = "";
			switch(qwwl.getStatus()){
			case 1:
				statusValue = "提现中";
				break;
			case 2:
				statusValue = "提现成功";
				break;
			case 3:
				statusValue = "提现失败";
				break;
			}
			map.put("status", qwwl.getStatus()+"");//提现状态：1提现中 2提现成功 3提现失败
			map.put("statusValue", statusValue);//提现状态：1提现中 2提现成功 3提现失败
			map.put("createTime", sdf.format(qwwl.getCreateTime()));
			list.add(map);
		}
		
    	json.put("result", "0");
		json.put("description", "获取列表成功");
		json.put("list", list);
		json.put("count", qwwlListAll.size());
		return buildReqJsonObject(json);
	}
	

	/**
	 * 商家发货
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value = "deal", method = RequestMethod.POST)
	@ResponseBody
	public String sendOrder() throws Exception {
		JSONObject json = new JSONObject();
		if (sign == 1) {
			json.put("result", "1");
			json.put("description", "请检查参数格式是否正确或者参数是否完整");
			return buildReqJsonInteger(1, json);
		}
		// 登录认证失败
		if (sign == 2) {
			json.put("result", "2");
			json.put("description", "账号未登录");
			return buildReqJsonInteger(2, json);
		}
		
		HttpSession session = request.getSession();
		Manager manager = (Manager) session.getAttribute("MANAGER");
        if(manager == null){
        	json.put("result", "1");
			json.put("description", "账号未登陆");
			return buildReqJsonObject(json);
        }
		
		JSONObject bodyInfo = JSONObject.fromObject(bodyString);
		int right = 1;
		if(bodyInfo.get("id") == null || "".equals(bodyInfo.get("id"))) {
			right = 0;
		}else if(bodyInfo.get("type") == null || "".equals(bodyInfo.get("type"))){
			right = 0;
		}
		if(right == 0){
			json.put("result", "1");
			json.put("description", "操作失败，请检查输入的参数是否完整");
			return buildReqJsonObject(json);
		}
		
		QqbsWithdrawalsLog qwwl = qqbsWithdrawalsLogService.selectByPrimaryKey(Integer.valueOf(bodyInfo.getString("id")));
		
		if(qwwl == null){
			json.put("result", "3");
			json.put("description", "操作失败，不存在该提现记录");
			return buildReqJsonObject(json);
		}
		
		QqbsReward qr = qqbsRewardService.selectByAccountId(qwwl.getAccountId());
		
		//1同意；0拒绝
		if("1".equals(bodyInfo.getString("type"))){
			
			AccountOpenid ao = accountOpenidService.selectByAccountId(qwwl.getAccountId());
			if(ao == null){
				json.put("result", "1");
				json.put("description", "用户openid查询不到");
				return buildReqJsonObject(json);
			}
			//打款
            RequestHandler reqHandler = new RequestHandler(null, null);
            String nonce_str = MD5Util.getNonceStr();
            
            reqHandler.setParameter("mch_appid","wx7356cc10aab105d2"); // 公众账号ID
            reqHandler.setParameter("mchid","1499693572"); // 商户号
            //随机字符串
            reqHandler.setParameter("nonce_str", nonce_str); 
            // 商家订单号
            reqHandler.setParameter("partner_trade_no", MD5Util.getNonceStr());
            //用户openid
            reqHandler.setParameter("openid", ao.getOpenId());
            //校验用户姓名选项
            reqHandler.setParameter("check_name", "NO_CHECK");
            //金额
            reqHandler.setParameter("amount", (int)(qwwl.getWithdrawals() * 100) + "");
            //企业付款描述信息
            reqHandler.setParameter("desc", "商盟惠购");
            //Ip地址
            reqHandler.setParameter("spbill_create_ip", request.getRemoteAddr());
            
             //key
            reqHandler.setKey("a1av897793acfc199182a649e905daab");
            
            // 生成签名
            String sign = reqHandler.createSign(reqHandler.getParameters());
            reqHandler.setParameter("sign", sign);
            String requestUrl = reqHandler.getRequestURL();
            //微信服务路径
            String cashUrl = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";
            //商户号码
            String mchid = "1499693572";
            //下载的商户平台证书路径
            String certPath = "/lawyer/config/apiclient_cert.p12";
            System.out.println(cashUrl);
            System.out.println(mchid);
            System.out.println(certPath);
            System.out.println(requestUrl);
            
            com.alibaba.fastjson.JSONObject responseParams = CommonHttpClient.sendXmlRefundHTTP(cashUrl, mchid, certPath, requestUrl);	 
            System.out.println("下来了");
            if ("SUCCESS".equals(responseParams.getString("return_code")) && "SUCCESS".equals(responseParams.getString("result_code")))
            {
                //1.提现成功*/
            	qwwl.setStatus((byte)2);
    			Integer updateQwwl = qqbsWithdrawalsLogService.updateByPrimaryKeySelective(qwwl);
    			if(qr!= null && updateQwwl == 1){
    				if(qr != null){
                        float newCash = qr.getAlreadyCash()+qwwl.getWithdrawals();
                        float totalcash=qr.getTotalReward();
                        qr.setAlreadyCash(newCash);
                        if(totalcash-newCash<0){
                        	qr.setWithdrawCash(0f);
                        }else{
                        	qr.setWithdrawCash(totalcash-newCash);
                        }
                        int updateQr = qqbsRewardService.updateByPrimaryKeySelective(qr);
                        if(updateQr==1){
                        	json.put("result", "1");
            				json.put("description", "同意提现成功");
            				return buildReqJsonObject(json);
                        }else{
                        	json.put("result", "1");
            				json.put("description", "更新奖励记录失败,同意提现失败");
            				return buildReqJsonObject(json);
                        }
                    }
    			}else{
    				json.put("result", "1");
    				json.put("description", "更新提现Log失败,同意提现失败");
    			}
                
            }else if ("SUCCESS".equals(responseParams.getString("return_code")) && "FAIL".equals(responseParams.getString("result_code")))
            {
            	json.put("result", "1");
				json.put("description", responseParams.getString("err_code_des") + "");
				return buildReqJsonObject(json);
            }
		}else{
			qwwl.setStatus((byte)3);
			Integer updateQwwl = qqbsWithdrawalsLogService.updateByPrimaryKeySelective(qwwl);
			if(qr!= null && updateQwwl == 1){
				float newCash = qr.getWithdrawCash()+qwwl.getWithdrawals();
				qr.setWithdrawCash(newCash);
				Integer updateQr = qqbsRewardService.updateByPrimaryKeySelective(qr);
				if(updateQr == 1){
					json.put("result", "0");
					json.put("description", "拒绝提现成功");
				}else{
					json.put("result", "1");
					json.put("description", "更新奖励记录失败,拒绝提现失败");
				}
			}else{
				json.put("result", "1");
				json.put("description", "更新提现Log失败,拒绝提现失败");
			}
		}
		return buildReqJsonObject(json);
	}
}
